package com.yihengyi.demo.test;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

public class CustomClientHttpRequestFactoryWithSSL extends HttpComponentsClientHttpRequestFactory {

    public CustomClientHttpRequestFactoryWithSSL() {
        super();
        try {
            // 直接实例化CustomTrustManager
            TrustManager customTrustManager = new CustomTrustManager();

            // 初始化SSLContext并使用CustomTrustManager
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{customTrustManager}, new java.security.SecureRandom());

            // 使用自定义的SSLContext创建CloseableHttpClient
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLContext(sslContext)
                    // 使用NoopHostnameVerifier来关闭主机名验证
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

            // 设置自定义的httpClient到HttpComponentsClientHttpRequestFactory
            setHttpClient(httpClient);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException("Failed to create HttpClient with custom SSL context", e);
        }
    }
}
